package io.rong.app;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import cn.yueliangbaba.R;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.Location;
import com.tencent.lbssearch.object.param.Geo2AddressParam;
import com.tencent.lbssearch.object.result.Geo2AddressResultObject;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.mapsdk.raster.model.GeoPoint;
import com.tencent.mapsdk.raster.model.LatLng;
import com.tencent.tencentmap.mapsdk.map.MapActivity;
import com.tencent.tencentmap.mapsdk.map.MapView;

import io.rong.app.DemoContext;
import io.rong.message.LocationMessage;

/**
 * Created by DragonJ on 14/11/21.
 */

@SuppressLint("ClickableViewAccessibility")
public class SOSOLocationActivity extends MapActivity implements
        TencentLocationListener,View.OnTouchListener {

	double mLat,mLng;
	String mAddress;
    MapView mMapView;
    Button mButton = null;
    LocationMessage mMsg;

    private HandlerThread mHandlerThread;

    @Override
    /**
     *显示地图，启用内置缩放控件，并用MapController控制地图的中心点及Zoom级别
     */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.de_ac_soso_map);

        mHandlerThread = new HandlerThread("LocationThread");
        mHandlerThread.start();
        mWorkHandler = new Handler(mHandlerThread.getLooper());
        
        if (getIntent().hasExtra("location")) {
            mMsg = getIntent().getParcelableExtra("location");
        }
        
        initView();
        if (mMsg != null)
            mButton.setVisibility(View.GONE);
        
        mMapView.getUiSettings().setAnimationEnabled(true);

        if (mMsg == null) {
            GeoPoint point = new GeoPoint((int) (39.90923 * 1E6), (int) (116.397428 * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度

            mMapView.setOnTouchListener(this);
            mMapView.getController().setCenter(point);
            mMapView.getController().setZoom(16);
            TencentLocationRequest request = TencentLocationRequest.create();
            TencentLocationManager.getInstance(this).requestLocationUpdates(request, this);
        } else {
            GeoPoint point = new GeoPoint((int) (mMsg.getLat() * 1E6), (int) (mMsg.getLng() * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度

            ((TextView)findViewById(android.R.id.title)).setText(mMsg.getPoi());
            findViewById(android.R.id.icon).setVisibility(View.VISIBLE);
            mMapView.getController().setCenter(point);
            mMapView.getController().setZoom(16);
        }
    }


    private void initView() {
        mMapView = (MapView) findViewById(android.R.id.widget_frame);
        mButton = (Button) this.findViewById(R.id.right);
        
        ((Button) findViewById(R.id.right)).setText("确定");
        ((TextView) findViewById(R.id.center)).setText("我的位置");
        findViewById(R.id.left).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				finish();
			}
        });
        findViewById(R.id.right).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				if(mAddress != null)
				{
		            Uri uri = Uri
		                    .parse("http://apis.map.qq.com/ws/staticmap/v2").buildUpon()
		                    .appendQueryParameter("size", "240*240")
		                    .appendQueryParameter("key", "CE6BZ-XTXHP-WRIDS-LGMQL-C5YEE-I7FSC")
		                    .appendQueryParameter("zoom", "16")
		                    .appendQueryParameter("center", mLat
		                            + ","
		                            + mLng).build();

		            LocationMessage mMsg = LocationMessage.obtain(mLat,
		            		mLng, mAddress, uri);
					
					DemoContext.getInstance().getLastLocationCallback().onSuccess(mMsg);  
					DemoContext.getInstance().setLastLocationCallback(null);  
				}
	            finish();  				
			}
        });
    }

    @Override
    public void onLocationChanged(final TencentLocation tencentLocation,
                                  int code, String s) {
        if (TencentLocation.ERROR_OK == code) {
            mLat = tencentLocation.getLatitude();
            mLng = tencentLocation.getLongitude();
            mAddress = tencentLocation.getAddress();
            
            GeoPoint point = new GeoPoint((int) (tencentLocation.getLatitude() * 1E6),
                    (int) (tencentLocation.getLongitude() * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度

            ((TextView)findViewById(android.R.id.title)).setText(tencentLocation.getAddress());
            findViewById(android.R.id.icon).setVisibility(View.VISIBLE);
            mMapView.getController().setCenter(point);
            mMapView.getController().setZoom(16);
            
            TencentLocationManager.getInstance(this).removeUpdates(this);
        } else {
            Toast.makeText(this, "定位失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onStatusUpdate(String s, int i, String s2) {

    }

    @Override
    protected void onDestroy() {
        if (DemoContext.getInstance().getLastLocationCallback() != null)
            DemoContext.getInstance().getLastLocationCallback().onFailure("失败");

        DemoContext.getInstance().setLastLocationCallback(null);
        TencentLocationManager.getInstance(this).removeUpdates(this);

        super.onDestroy();
    }
    
    POISearchRunnable mLastSearchRunnable;
    Handler mWorkHandler;
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mLastSearchRunnable != null)
                    mWorkHandler.removeCallbacks(mLastSearchRunnable);
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                mLastSearchRunnable = new POISearchRunnable();
                mWorkHandler.post(new POISearchRunnable());
                break;
            default:
                break;
        }

        return false;
    }

    Handler handler = new Handler(){
    	public void handleMessage(Message msg)
    	{
            GeoPoint point = new GeoPoint((int) (mLat * 1E6),
                    (int) (mLng * 1E6)); // 用给定的经纬度构造一个GeoPoint，单位是微度

            ((TextView)findViewById(android.R.id.title)).setText(mAddress);
            findViewById(android.R.id.icon).setVisibility(View.VISIBLE);
            mMapView.getController().setCenter(point);
            mMapView.getController().setZoom(16);
    	}
    };

    private class POISearchRunnable implements Runnable {

        public void run() {

            try {
                float lat = (float) mMapView.getMap().getMapCenter().getLatitude();
                float lng = (float) mMapView.getMap().getMapCenter().getLongitude();
                
                mLat = lat;
                mLng = lng;

                Location location = new Location(lat, lng);
                if (location == null)
                    return;

                TencentSearch tencentSearch = new TencentSearch(SOSOLocationActivity.this);
                Geo2AddressParam geo2AddressParam = new Geo2AddressParam().
                        location(location).get_poi(true);

                tencentSearch.geo2address(geo2AddressParam, new HttpResponseListener() {

                    @Override
                    public void onSuccess(int arg0, Header[] arg1, BaseObject arg2) {
                        if (arg2 == null)
                            return;

                        Geo2AddressResultObject obj = (Geo2AddressResultObject) arg2;
                        mAddress = obj.result.address;
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
